import COS from 'cos-js-sdk-v5';
import { systemApi } from '/@/api';

const SystemApi = systemApi();

const upload = (file: any, Key: string) => {
	return new Promise((resolve, reject) => {
		SystemApi.tencentCosTmp()
			.then((res: any) => {
				console.log('获取腾讯云COS临时秘钥', res);
				let info = res.data.info;
				var cos = new COS({
					getAuthorization: (options, callback) => {
						callback({
							TmpSecretId: info.TmpSecretId,
							TmpSecretKey: info.TmpSecretKey,
							SecurityToken: info.SecurityToken,
							StartTime: info.StartTime,
							ExpiredTime: info.ExpiredTime,
						});
					},
				});
				cos.putObject(
					{
						Bucket: info.Bucket /* 必须 */,
						Region: info.Region /* 存储桶所在地域，必须字段 */,
						Key: Key /* 必须 */,
						StorageClass: 'STANDARD',
						Body: file,
						onProgress: (progressData) => {
							console.log('上传中', JSON.stringify(progressData));
						},
					},
					(err, data) => {
						console.log('err, data', err, data);
						if (data) {
							resolve({ statusCode: data.statusCode || 10000, url: import.meta.env.VITE_FILE_API + Key });
						} else {
							resolve({ err: err ? err : '' });
						}
					}
				);
			})
			.catch((err: any) => {
				reject(err);
			});
	});
};
export default upload;
